<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/facicon.ico?v=5.1.4" color="#222">





  <meta name="keywords" content="JavaScript,jQuery,AJAX,">





  <link rel="alternate" href="/atom.xml" title="Key" type="application/atom+xml">






<meta name="description" content="AJAX即’Asynchronous Javascript And XML’(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术.   AJAX = 异步 JavaScript和XML(标准通用标记语言的子集).AJAX是一种用于创建快速动态网页的技术.AJAX是一种在无需重新加载整个页面的情况下,能够更新部分网页的技术.通过在后台与服务器进行少量数据交换,AJAX可以使">
<meta name="keywords" content="JavaScript,jQuery,AJAX">
<meta property="og:type" content="article">
<meta property="og:title" content="Ajax">
<meta property="og:url" content="https://blog.qipo.net/2017/08/29/ajax/index.html">
<meta property="og:site_name" content="Key">
<meta property="og:description" content="AJAX即’Asynchronous Javascript And XML’(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术.   AJAX = 异步 JavaScript和XML(标准通用标记语言的子集).AJAX是一种用于创建快速动态网页的技术.AJAX是一种在无需重新加载整个页面的情况下,能够更新部分网页的技术.通过在后台与服务器进行少量数据交换,AJAX可以使">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-06-03T02:37:45.135Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Ajax">
<meta name="twitter:description" content="AJAX即’Asynchronous Javascript And XML’(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术.   AJAX = 异步 JavaScript和XML(标准通用标记语言的子集).AJAX是一种用于创建快速动态网页的技术.AJAX是一种在无需重新加载整个页面的情况下,能够更新部分网页的技术.通过在后台与服务器进行少量数据交换,AJAX可以使">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://blog.qipo.net/2017/08/29/ajax/">





  <title>Ajax | Key</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Key</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description"></h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://blog.qipo.net/2017/08/29/ajax/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Key">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Key">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Ajax</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-29T08:16:54+08:00">
                2017-08-29
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  4.5k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  17
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>AJAX即’Asynchronous Javascript And XML’(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术.  </p>
<p>AJAX = 异步 JavaScript和XML(标准通用标记语言的子集).<br>AJAX是一种用于创建快速动态网页的技术.<br>AJAX是一种在无需重新加载整个页面的情况下,能够更新部分网页的技术.通过在后台与服务器进行少量数据交换,AJAX可以使网页实现异步更新.这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新.<br>传统的网页(不使用AJAX)如果需要更新内容,必须重载整个网页页面.</p>
<h2 id="AJAX技术"><a href="#AJAX技术" class="headerlink" title="AJAX技术"></a>AJAX技术</h2><p>AJAX技术的核心是XMLHttpRequest对象(简称 XHR),XHR为向服务器发送请求和解析服务器想赢提供了流畅的借口.能够以异步方式从服务器取得更多信息,意味着用户单击后,可以不必刷新页面也可以取得新数据,也就是说,可以使用XHR对象取得新数据,然后再通过DOM将新数据插入到页面中.另外,虽然名字中包含XML的成分,但AJAX通信与数据格式无关;这种技术就是无需刷新页面即可从服务器取得数据,但不一定是XML数据.</p>
<ul>
<li>定义： ajax是用于客户端和服务端进行异步数据交互，在无需刷新整个页面的情况下实现局部数据更新的一种技术。</li>
<li>特点： 前后端通信，异步方式通信，无刷新，局部更新。</li>
</ul>
<p>优点:</p>
<ol>
<li>最大的一点是页面无刷新，用户的体验非常好。</li>
<li>使用异步方式与服务器通信，具有更加迅速的响应能力。</li>
<li>可以把以前一些服务器负担的工作转嫁到客户端，利用客户端闲置的能力来处理，减轻服务器和带宽的负担，节约空间和宽带租用成本。并且减轻服务器的负担，ajax的原则是“按需取数据”，可以最大程度的减少冗余请求，和响应对服务器造成的负担。</li>
<li>基于标准化的并被广泛支持的技术，不需要下载插件或者小程序。</li>
</ol>
<p>缺点:</p>
<ol>
<li>ajax不支持浏览器back按钮。</li>
<li>安全问题 AJAX暴露了与服务器交互的细节。</li>
<li>对搜索引擎的支持比较弱。</li>
<li>破坏了程序的异常机制。</li>
<li>不容易调试。</li>
</ol>
<h2 id="原生XHR对象应用"><a href="#原生XHR对象应用" class="headerlink" title="原生XHR对象应用"></a>原生XHR对象应用</h2><h3 id="创建XMLHttpRequest对象"><a href="#创建XMLHttpRequest对象" class="headerlink" title="创建XMLHttpRequest对象"></a>创建XMLHttpRequest对象</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 兼容低版本ie浏览器的代码,对于现代浏览器可以省略部分代码</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createXHR</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> XMLHttpRequest != <span class="string">"undefined"</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> XMLHttpRequest();</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">typeof</span> ActiveXObject != <span class="string">"undefined"</span>)&#123;</span><br><span class="line">         <span class="keyword">if</span> (<span class="keyword">typeof</span> <span class="built_in">arguments</span>.callee.activeXString != <span class="string">"string"</span>)&#123;</span><br><span class="line">            <span class="keyword">var</span> versions = [ <span class="string">"MSXML2.XMLHttp.6.0"</span>, <span class="string">"MSXML2.XMLHttp.3.0"</span>,</span><br><span class="line">            <span class="string">"MSXML2.XMLHttp"</span>], i, len;</span><br><span class="line">            <span class="keyword">for</span> (i=<span class="number">0</span>,len=versions.length; i &lt; len; i++)&#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    <span class="keyword">new</span> ActiveXObject(versions[i]);</span><br><span class="line">                    <span class="built_in">arguments</span>.callee.activeXString = versions[i];</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                &#125; <span class="keyword">catch</span> (ex)&#123;</span><br><span class="line">                    <span class="comment">//跳过</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ActiveXObject(<span class="built_in">arguments</span>.callee.activeXString);</span><br><span class="line">     &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">"No XHR object available."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面大堆的代码仅仅是为了兼容低版本的IE浏览器,对于现代的大部分浏览器而言,上面的大部分代码都是冗余的,只需要几行代码,如下:</p>
<figure class="highlight actionscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createXHR</span><span class="params">()</span></span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> XMLHttpRequest();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面分别是老版本的IE浏览器和现在浏览器的创建函数.<br>现在需要调用这个函数生成一个实例化对象.</p>
<figure class="highlight ebnf"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">var xhr</span> = createXHR();</span><br></pre></td></tr></table></figure>
<p>当然对于现在大部分浏览器而言,上面的两个步骤可以缩减为一个步骤:</p>
<figure class="highlight haxe"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> xhr = <span class="keyword">new</span> <span class="type">XMLHttpRequest</span>();</span><br></pre></td></tr></table></figure>
<p><code>XMLHttpRequest()</code>构造函数,初始化一个XMLHttpRequest对象,必须在所有其他方法被调用前调用构造函数.此处用于AJAX通信.</p>
<h3 id="open-初始化一个请求"><a href="#open-初始化一个请求" class="headerlink" title="open() 初始化一个请求"></a>open() 初始化一个请求</h3><p>使用XHR对象时,要调用的第一个方法就是<code>open()</code>,初始化一个请求,方法用于JAVAScript代码中,这个方法有以下参数</p>
<figure class="highlight oxygene"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">void open(</span><br><span class="line">   DOMString <span class="function"><span class="keyword">method</span>,</span></span><br><span class="line"><span class="function">   <span class="title">DOMString</span> <span class="title">url</span>,</span></span><br><span class="line"><span class="function">   <span class="title">optional</span> <span class="title">boolean</span> <span class="title">async</span>,</span></span><br><span class="line"><span class="function">   <span class="title">optional</span> <span class="title">DOMString</span> <span class="title">user</span>,</span></span><br><span class="line"><span class="function">   <span class="title">optional</span> <span class="title">DOMString</span> <span class="title">password</span></span></span><br><span class="line"><span class="function">);</span></span><br></pre></td></tr></table></figure>
<p>参数:   </p>
<ul>
<li>method:请求所使用的HTTP方法,例如:’GET’,’POST’等.</li>
<li>url:该请求所要访问的URL</li>
<li>async:一个可选的布尔值参数,默认为true,意味着是否执行异步操作,如果值为false,则send()方法不会返回任何东西,直到接受到了服务器的返回数据.</li>
<li>user:可选参数,为授权使用;默认参数为空String.</li>
<li>password:可选参数,为授权使用;默认参数为空String.</li>
</ul>
<blockquote>
<p>对于这个方法,我们只需要前面的3个参数,关于代码:<br>一是URL相对于执行代码的当前页面(当然也可以使用绝对路径);<br>二是调用open()方法并不会真正的发送请求,而只是启动一个请求以备发送<br>三是关于第三个参数异步,异步：客户端发送请求之后，不用死等服务端的响应，可以继续先做自己的事。服务端什么时候响应，那客户端就什么时候接收响应。</p>
</blockquote>
<h3 id="send-发送一个请求"><a href="#send-发送一个请求" class="headerlink" title="send() 发送一个请求"></a>send() 发送一个请求</h3><p>发送请求.如果该请求是异步模式(默认),该方法会立即返回.相反,如果请求是同步模式,则直到请求的响应完全接受以后,该方法才会返回.<br>XMLHttpRequest.send()接受一个可选的参数,其作为请求主体,如果请求方法是GET,其数据携带在URL上,则应将请求主体设置为null.</p>
<h3 id="接受响应"><a href="#接受响应" class="headerlink" title="接受响应"></a>接受响应</h3><p>在收到响应后,响应的数据会自动填充XHR对象的属性,相关属性简介如下:<br><code>onreadystatechange</code>:一个JAVAScript函数对象,当<code>readyState</code>属性改变时调用它.<br><code>readyState</code>:见下.<br><code>responseText</code>:作为响应的主体被返回的文本.<br><code>reponseXML</code>:如果响应的内容类型是<code>text/xml</code>或<code>application/xml</code>,这个属性中保存包含着响应数据的XML DOM文档.<br><code>status</code>:响应的HTTP状态.<br><code>statusTest</code>:HTTP状态说明.    </p>
<p>多数情况下,我们还是要发送异步请求,才能让JAVAScript继续执行下去而不必等待响应.此时,我们可以检测XHR对象的readyState属性,该属性表示请求响应过程的当前活动阶段.这个属性可取的值如下:</p>
<ul>
<li>0:未初始化.尚未调用open()方法.</li>
<li>1:启动.已经调用open()方法.</li>
<li>2:发送.已经调用send()方法,但尚未接收到响应.</li>
<li>3:接受.已经接收到部分响应数据.</li>
<li>4:完成.已经接受到全部响应数据,而且已经可以在客户端使用了.</li>
<li>只要readyState属性的值由一个值变成另外一个值,都会触发一次readystatechange事件.</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line">$(<span class="string">"#start"</span>).click(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line"></span><br><span class="line">      <span class="comment">//1. 想要使用ajax，必须要先创建xhr对象</span></span><br><span class="line">      <span class="comment">//此处的xhr用于ajax通信</span></span><br><span class="line">      <span class="keyword">var</span> xhr = createXHR();</span><br><span class="line"></span><br><span class="line">      <span class="comment">//高版本浏览器</span></span><br><span class="line">      <span class="comment">// var xhr = new XMLHttpRequest();</span></span><br><span class="line"></span><br><span class="line">      <span class="comment">//2. 准备向服务器发送一次http请求(get, post)</span></span><br><span class="line">      <span class="comment">/*</span></span><br><span class="line"><span class="comment">      true表示是异步请求</span></span><br><span class="line"><span class="comment">      异步：客户端发送请求之后，不用死等服务端的响应，可以继续先做自己的事。</span></span><br><span class="line"><span class="comment">      服务端什么时候响应，那客户端就什么时候接收响应。</span></span><br><span class="line"><span class="comment">      */</span></span><br><span class="line"></span><br><span class="line">      <span class="comment">//数据格式  url?key=value&amp;key=value</span></span><br><span class="line">      xhr.open(<span class="string">"get"</span>, <span class="string">"http://127.0.0.1:8000/index?name=张三&amp;age=22&amp;score=88"</span>, <span class="literal">true</span>);</span><br><span class="line"></span><br><span class="line">      <span class="comment">//用于转码用的</span></span><br><span class="line">      <span class="comment">// console.log(encodeURIComponent("张三 李四 xxx yyy ))) * /~skjkjh"));</span></span><br><span class="line"></span><br><span class="line">      <span class="comment">//4. 用于时刻准备接受服务端的响应</span></span><br><span class="line">      xhr.onreadystatechange = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="comment">// console.log("当前状态： " + xhr.readyState);</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//当状态为4时，表示响应完成， 失败？成功？</span></span><br><span class="line">        <span class="keyword">if</span> (xhr.readyState === <span class="number">4</span>)&#123;</span><br><span class="line">          <span class="keyword">if</span> ((xhr.status &gt;= <span class="number">200</span>) &amp;&amp; (xhr.status &lt; <span class="number">400</span>))&#123;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//通过xhr.response得到后端发送来的数据</span></span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"recv from server: "</span>, xhr.response);</span><br><span class="line"></span><br><span class="line">            $(<span class="string">"&lt;h1&gt;success&lt;/h1&gt;"</span>).appendTo(<span class="string">"body"</span>);</span><br><span class="line">          &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            $(<span class="string">"&lt;h1&gt;fail&lt;/h1&gt;"</span>).appendTo(<span class="string">"body"</span>);</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;;</span><br><span class="line"></span><br><span class="line">      <span class="comment">//3. 真正发送一次请求</span></span><br><span class="line">      <span class="comment">//get请求，数据携带在url上，所有send为空即可</span></span><br><span class="line">      xhr.send();</span><br><span class="line">      $(<span class="string">"&lt;h1&gt;send完毕!&lt;/h1&gt;"</span>).appendTo(<span class="string">"body"</span>);</span><br><span class="line">    &#125;);</span><br></pre></td></tr></table></figure>
<h3 id="GET请求"><a href="#GET请求" class="headerlink" title="GET请求"></a>GET请求</h3><p>上面的代码就是一次完整的GET请求<br>GET是最常见的请求类型,最常用于向服务器查询某些信息.必要时,可以将查询字符串参数追加到URL的末尾,以便将信息发送给服务器.对XHR而言,位于传入open()方法的URL末尾的查询字符串必须经过正确的编码才行.<br><code>encodeURLComponent()</code>是对统一资源标示符(URL)的组成部分进行编码的方法.它使用一到四个转义序列来表示字符串中的的每个字符的UTF-8编码.它会转义除了字母,数字,<code>(</code>,<code>)</code>,<code>.</code>,<code>!</code>,<code>~</code>,<code>*</code>,<code>&#39;</code>,<code>-</code>和<code>_</code>之外的所有字符.<br>为了避免服务器收到不可预计的请求,对任何用户输入的作为URL部分的内容你都需要用<code>encodeURLComponent</code>进行转义.比如,一个用户可能会输入<code>Teyme &amp;time=again</code>作为comment变量的一部分.如果不使用<code>encodeURLComponent</code>对此内容进行转义,服务器得到的将是<code>commnet=Teyme%20&amp;time=again</code>.请注意,<code>&amp;</code>符号和<code>=</code>符号产生了一个新的键值对,所以服务器将得到两个键值对(一个键值对是comment=Teyme另一个则是time=again),而不是一个键值对.</p>
<h3 id="POST请求"><a href="#POST请求" class="headerlink" title="POST请求"></a>POST请求</h3><p>使用频率仅次于GET的是POST请求,通常用于向服务器发送应该被保存的数据.POST请求应该把数据作为主体提交,而GET请求传统上不是这样的.POST请求的主体可以包含非常多的数据,而且格式不限.<br>默认情况下,服务器对POST请求和提交Web表单的请求并不会一视同仁.因此,服务器端必须有程序来读取发送过来的原始数据,并从中解析出有用的部分.不过,我们可以使用XHR来模仿表单提交:首先将Content-Type头部信息设置为 <code>application/x-www-form-urlencoded</code>,也就是表单提交时的内容类型,其次是以适当的格式创建一个字符串.</p>
<figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//发送post数据时，按照form表单的数据格式进行发送</span></span><br><span class="line"><span class="comment">//需要设置http的头部来指定要发送的数据格式</span></span><br><span class="line"><span class="selector-tag">xhr</span><span class="selector-class">.setRequestHeader</span>(<span class="string">"Content-Type"</span>, <span class="string">"application/x-www-form-urlencoded"</span>);</span><br><span class="line"></span><br><span class="line"><span class="selector-tag">xhr</span><span class="selector-class">.send</span>(<span class="string">"name=lisi&amp;age=22&amp;score=88"</span>);</span><br></pre></td></tr></table></figure>
<p>由于,POSt请求不是通过URL实现的,所以URL也不必携带参数,完整的一次post请求如下:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"utf-8"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>ajax使用的基本步骤<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">button</span> <span class="attr">id</span>=<span class="string">"start"</span>&gt;</span>ajax<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"./js/jquery.min.js"</span> <span class="attr">charset</span>=<span class="string">"utf-8"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">    <span class="comment">// 兼容低版本ie浏览器的代码,对于现代浏览器可以省略部分代码</span></span></span><br><span class="line"><span class="actionscript">    <span class="function"><span class="keyword">function</span> <span class="title">createXHR</span><span class="params">()</span></span>&#123;</span></span><br><span class="line"><span class="actionscript">      <span class="keyword">if</span> (<span class="keyword">typeof</span> XMLHttpRequest != <span class="string">"undefined"</span>)&#123;</span></span><br><span class="line"><span class="actionscript">        <span class="keyword">return</span> <span class="keyword">new</span> XMLHttpRequest();</span></span><br><span class="line"><span class="actionscript">      &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">typeof</span> ActiveXObject != <span class="string">"undefined"</span>)&#123;</span></span><br><span class="line"><span class="javascript">        <span class="keyword">if</span> (<span class="keyword">typeof</span> <span class="built_in">arguments</span>.callee.activeXString != <span class="string">"string"</span>)&#123;</span></span><br><span class="line"><span class="actionscript">          <span class="keyword">var</span> versions = [ <span class="string">"MSXML2.XMLHttp.6.0"</span>, <span class="string">"MSXML2.XMLHttp.3.0"</span>,</span></span><br><span class="line"><span class="actionscript">          <span class="string">"MSXML2.XMLHttp"</span>], i, len;</span></span><br><span class="line"><span class="actionscript">          <span class="keyword">for</span> (i=<span class="number">0</span>,len=versions.length; i &lt; len; i++)&#123;</span></span><br><span class="line"><span class="actionscript">            <span class="keyword">try</span> &#123;</span></span><br><span class="line"><span class="actionscript">              <span class="keyword">new</span> ActiveXObject(versions[i]);</span></span><br><span class="line"><span class="javascript">              <span class="built_in">arguments</span>.callee.activeXString = versions[i];</span></span><br><span class="line"><span class="actionscript">              <span class="keyword">break</span>;</span></span><br><span class="line"><span class="actionscript">            &#125; <span class="keyword">catch</span> (ex)&#123;</span></span><br><span class="line"><span class="actionscript">              <span class="comment">//跳过</span></span></span><br><span class="line"><span class="undefined">            &#125;</span></span><br><span class="line"><span class="undefined">          &#125;</span></span><br><span class="line"><span class="undefined">        &#125;</span></span><br><span class="line"><span class="javascript">        <span class="keyword">return</span> <span class="keyword">new</span> ActiveXObject(<span class="built_in">arguments</span>.callee.activeXString);</span></span><br><span class="line"><span class="actionscript">      &#125; <span class="keyword">else</span> &#123;</span></span><br><span class="line"><span class="javascript">        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">"No XHR object available."</span>);</span></span><br><span class="line"><span class="undefined">      &#125;</span></span><br><span class="line"><span class="undefined">    &#125;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="javascript">    $(<span class="string">"#start"</span>).click(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">      <span class="comment">//1. 想要使用ajax，必须要先创建xhr对象</span></span></span><br><span class="line"><span class="actionscript">      <span class="comment">//此处的xhr用于ajax通信</span></span></span><br><span class="line"><span class="actionscript">      <span class="keyword">var</span> xhr = createXHR();</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">      <span class="comment">//高版本浏览器</span></span></span><br><span class="line"><span class="actionscript">      <span class="comment">// var xhr = new XMLHttpRequest();</span></span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">      <span class="comment">//2. 准备向服务器发送一次http请求(get, post)</span></span></span><br><span class="line"><span class="undefined">      /*</span></span><br><span class="line"><span class="actionscript">      <span class="literal">true</span>表示是异步请求</span></span><br><span class="line"><span class="undefined">      异步：客户端发送请求之后，不用死等服务端的响应，可以继续先做自己的事。</span></span><br><span class="line"><span class="undefined">      服务端什么时候响应，那客户端就什么时候接收响应。</span></span><br><span class="line"><span class="undefined">      */</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">      xhr.open(<span class="string">"post"</span>, <span class="string">"http://127.0.0.1:8000/index"</span>, <span class="literal">true</span>);</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">      <span class="comment">//4. 用于时刻准备接受服务端的响应</span></span></span><br><span class="line"><span class="actionscript">      xhr.onreadystatechange = <span class="function"><span class="keyword">function</span> <span class="params">()</span> </span>&#123;</span></span><br><span class="line"><span class="actionscript">        <span class="comment">// console.log("当前状态： " + xhr.readyState);</span></span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">        <span class="comment">//当状态为4时，表示响应完成， 失败？成功？</span></span></span><br><span class="line"><span class="actionscript">        <span class="keyword">if</span> (xhr.readyState === <span class="number">4</span>)&#123;</span></span><br><span class="line"><span class="actionscript">          <span class="keyword">if</span> ((xhr.status &gt;= <span class="number">200</span>) &amp;&amp; (xhr.status &lt; <span class="number">400</span>))&#123;</span></span><br><span class="line"><span class="javascript">            $(<span class="string">"&lt;h1&gt;success&lt;/h1&gt;"</span>).appendTo(<span class="string">"body"</span>);</span></span><br><span class="line"><span class="actionscript">          &#125; <span class="keyword">else</span> &#123;</span></span><br><span class="line"><span class="javascript">            $(<span class="string">"&lt;h1&gt;fail&lt;/h1&gt;"</span>).appendTo(<span class="string">"body"</span>);</span></span><br><span class="line"><span class="undefined">          &#125;</span></span><br><span class="line"><span class="undefined">        &#125;</span></span><br><span class="line"><span class="undefined">      &#125;;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">      <span class="comment">//3. 真正发送一次请求</span></span></span><br><span class="line"><span class="actionscript">      <span class="comment">//post请求，数据应该在send中发送！！！！！</span></span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">      <span class="comment">//发送post数据时，按照form表单的数据格式进行发送</span></span></span><br><span class="line"><span class="actionscript">      <span class="comment">//需要设置http的头部来指定要发送的数据格式</span></span></span><br><span class="line"><span class="actionscript">      xhr.setRequestHeader(<span class="string">"Content-Type"</span>, <span class="string">"application/x-www-form-urlencoded"</span>);</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">      xhr.send(<span class="string">"name=lisi&amp;age=22&amp;score=88"</span>);</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="javascript">      $(<span class="string">"&lt;h1&gt;send完毕!&lt;/h1&gt;"</span>).appendTo(<span class="string">"body"</span>);</span></span><br><span class="line"><span class="undefined">    &#125;);</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="undefined">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="jQuery-中的-Ajax-应用"><a href="#jQuery-中的-Ajax-应用" class="headerlink" title="jQuery 中的 Ajax 应用"></a>jQuery 中的 Ajax 应用</h2><p>jQuery库支持完整的Ajax操作.这里包含所有的函数和方法用于从服务端加载数据,并且不会导致页面刷新.</p>
<h3 id="底层接口"><a href="#底层接口" class="headerlink" title="底层接口"></a>底层接口</h3><ul>
<li><code>jQuery.ajax([setting])</code>其中<code>jQuery</code>等价于<code>$</code>,所以一般写成<code>$.ajax([setting])</code>.    </li>
<li><code>[setting]</code>是一个可选选项,一个以<code>{key:value}</code>组成的AJAX请求设置.其中的所有设置都是可选的,都有自己的默认值.   </li>
<li>说明: 执行一个异步的HTTP（Ajax）的请求。</li>
</ul>
<h4 id="常用的选项"><a href="#常用的选项" class="headerlink" title="常用的选项"></a>常用的选项</h4><p><strong>method</strong> (default:<code>&#39;GET&#39;</code>)<br>Type:<code>String</code><br>说明:HTTP的请求方法,例如:<code>POST</code>,<code>GET</code>.</p>
<hr>
<p><strong>url</strong>(default:当前页面的url)<br>Type:<code>String</code><br>说明:发送请求的地址.</p>
<hr>
<p><strong>data</strong><br>Type:<code>PlainObject</code>或<code>String</code>或<code>Array</code><br>说明:发送到服务器的数据。它被转换成一个查询字符串,如果已经是一个字符串的话就不会转换。查询字符串将被追加到GET请求的URL后面。参见 processData 选项说明，以防止这种自动转换。对象必须为”{键:值}”格式。如果这个参数是一个数组，jQuery会按照traditional 参数的值， 将自动转化为一个同名的多值查询字符串(查看下面的说明)。注：如 {foo:[“bar1”, “bar2”]} 转换为 ‘&amp;foo=bar1&amp;foo=bar2’。</p>
<hr>
<p><strong>dataType</strong>(default:<code>Intelligent Guess (xml, json, script, or html)</code>)<br>Type:<code>String</code><br>说明:从服务器返回你期望的数据类型.如果没有指定,jQuery将尝试通过MIME类型的响应信息来智能判断一个XML MIME类型就被识别为XML，在1.4中 JSON将生成一个JavaScript对象，在1.4中 script 将执行该脚本，其他任何类型会返回一个字符串）。 可用的类型（以及结果作为第一个参数传递给成功回调函数）有：</p>
<ul>
<li>“xml”: 返回 XML 文档，可以通过 jQuery 处理。</li>
<li>“html”: 返回纯文本 HTML 文本；包含的script标签会在插入DOM时执行。</li>
<li>“script”: 把响应的结果当作 JavaScript 执行，并将其当作纯文本返回。默认情况下会通过在URL中附加查询字符串变量 ，_=[TIMESTAMP]， 禁用缓存结果，除非设置了cache参数为true。注意: 在远程请求时(不在同一个域下)，所有POST请求都将转为GET请求。(注：因为将使用DOM的script标签来加载)</li>
<li>“json”:把响应的结果当作 JSON 执行，并返回一个JavaScript对象。跨域”json” 请求转换为”jsonp”，除非该请求在其请求选项中设置了jsonp:false。JSON 数据以严格的方式解析; 任何畸形的JSON将被拒绝，并且抛出解析错误信息。在jQuery1.9中，一个空响应也将被拒绝;服务器应该返回null或 {}响应代替。（见json.org的更多信息，正确的JSON格式。）</li>
<li>“jsonp”: 以 JSONP 的方式载入 JSON 数据块。会自动在所请求的URL最后添加”?callback=?”。默认情况下会通过在URL中附加查询字符串变量 ，_=[TIMESTAMP]， 禁用缓存结果，除非设置了cache参数为true。</li>
<li>“text”: 返回纯文本字符串。</li>
</ul>
<hr>
<p><strong>success</strong><br>Type:Function(<code>Anything</code> data,<code>String</code> textStatus,<code>jqXHR</code> jqXHR)<br>说明:请求成功后的回调函数.这个函数可以传递3个参数:</p>
<ul>
<li>从服务器返回的数据，并根据dataType参数进行处理后的数据或dataFilter回调函数，如果指定的话；</li>
<li>一个描述状态的字符串;</li>
<li>还有 jqXHR（在jQuery 1.4.x前为XMLHttpRequest） 对象 ;</li>
</ul>
<hr>
<p><strong>error</strong><br>Type:Function(<code>jqXHR</code> jqXHR, <code>String</code> textStatus, <code>String</code> errorThrown)<br>说明:请求失败时调用此函数。有以下三个参数：jqXHR (在 jQuery 1.4.x前为XMLHttpRequest) 对象、描述发生错误类型的一个字符串 和 捕获的异常对象。如果发生了错误，错误信息（第二个参数）除了得到null之外，还可能是”timeout”, “error”, “abort” ，和 “parsererror”。 当一个HTTP错误发生时，errorThrown 接收HTTP状态的文本部分，比如： “Not Found”（没有找到） 或者 “Internal Server Error.”（服务器内部错误）。 从jQuery 1.5开始, 在error设置可以接受函数组成的数组。每个函数将被依次调用。</p>
<h4 id="实例–登录"><a href="#实例–登录" class="headerlink" title="实例–登录"></a>实例–登录</h4><p>这个登录页面需要服务器支持,后端验证你输入的用户名,密码.当你的密码和用户名没有错时,会返回一个OK.验证错误就会返回一个FAIL</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"utf-8"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">title</span>&gt;</span>登录<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">style</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="undefined">    * &#123;</span></span><br><span class="line"><span class="undefined">      margin: 0;</span></span><br><span class="line"><span class="undefined">      padding: 0;</span></span><br><span class="line"><span class="undefined">    &#125;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="css">    <span class="selector-class">.login</span> &#123;</span></span><br><span class="line"><span class="undefined">      width: 500px;</span></span><br><span class="line"><span class="undefined">      margin: 50px auto;</span></span><br><span class="line"><span class="undefined">    &#125;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="css">    <span class="selector-class">.login</span> &gt; <span class="selector-tag">p</span> &#123;</span></span><br><span class="line"><span class="undefined">      color: red;</span></span><br><span class="line"><span class="undefined">      visibility: hidden;</span></span><br><span class="line"><span class="undefined">    &#125;</span></span><br><span class="line"><span class="undefined">  </span><span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"login"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">p</span>&gt;</span>用户名或者密码不能为空！<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">    用户名：<span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">name</span>=<span class="string">"username"</span>&gt;</span> <span class="tag">&lt;<span class="name">br</span>&gt;</span><span class="tag">&lt;<span class="name">br</span>&gt;</span> 密 码：<span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"passwd"</span> <span class="attr">name</span>=<span class="string">"password"</span>&gt;</span> <span class="tag">&lt;<span class="name">br</span>&gt;</span><span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">button</span> <span class="attr">id</span>=<span class="string">"btn"</span>&gt;</span>登录<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"></span><br><span class="line">  <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"./js/jquery.min.js"</span> <span class="attr">charset</span>=<span class="string">"utf-8"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="javascript">    $(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="javascript">      $(<span class="string">"#btn"</span>).click(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> username = $(<span class="string">".login input[name=username]"</span>).val();</span></span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> password = $(<span class="string">".login input[name=password]"</span>).val();</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">        <span class="keyword">if</span> ((!username) || (!password))&#123;</span></span><br><span class="line"><span class="actionscript">          <span class="comment">//如果为空的情况要执行</span></span></span><br><span class="line"><span class="javascript">          $(<span class="string">".login &gt; p"</span>).css(<span class="string">"visibility"</span>, <span class="string">"visible"</span>);</span></span><br><span class="line"><span class="actionscript">          <span class="keyword">return</span>;</span></span><br><span class="line"><span class="undefined">        &#125;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="undefined">        /*</span></span><br><span class="line"><span class="undefined">        用户的输入都是合法的，发送ajax登录请求</span></span><br><span class="line"><span class="undefined">        */</span></span><br><span class="line"><span class="javascript">        $.ajax(&#123;</span></span><br><span class="line"><span class="actionscript">           method: <span class="string">"post"</span>,</span></span><br><span class="line"><span class="actionscript">           url: <span class="string">"/login"</span>, <span class="comment">//直接填写路由即可</span></span></span><br><span class="line"><span class="undefined">           data: &#123;name: username, passwd: password&#125;,</span></span><br><span class="line"><span class="actionscript">           success: <span class="function"><span class="keyword">function</span><span class="params">(data, textStatus, jqXHR)</span></span>&#123;</span></span><br><span class="line"><span class="actionscript">             <span class="keyword">if</span> (data == <span class="string">"OK"</span>)&#123;</span></span><br><span class="line"><span class="actionscript">               <span class="comment">//登录</span></span></span><br><span class="line"><span class="javascript">               <span class="built_in">window</span>.location = <span class="string">"https://www.baidu.com"</span>; <span class="comment">//跳转页面</span></span></span><br><span class="line"><span class="actionscript">             &#125; <span class="keyword">else</span> &#123;</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">               <span class="comment">//将input的值设置为空</span></span></span><br><span class="line"><span class="javascript">               $(<span class="string">".login input"</span>).val(<span class="string">""</span>);</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="actionscript">               alert(<span class="string">"用户名和密码错误"</span>);</span></span><br><span class="line"><span class="undefined">             &#125;</span></span><br><span class="line"><span class="undefined">           &#125;,</span></span><br><span class="line"><span class="actionscript">           error: <span class="function"><span class="keyword">function</span><span class="params">(jqXHR, textStatus, error)</span></span>&#123;</span></span><br><span class="line"><span class="javascript">             <span class="built_in">console</span>.error(error);</span></span><br><span class="line"><span class="undefined">           &#125;</span></span><br><span class="line"><span class="undefined">        &#125;);</span></span><br><span class="line"><span class="undefined"></span></span><br><span class="line"><span class="undefined">      &#125;);</span></span><br><span class="line"><span class="undefined">    &#125;);</span></span><br><span class="line"><span class="undefined">  </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div></div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="Key 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Key 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/JavaScript/" rel="tag"># JavaScript</a>
          
            <a href="/tags/jQuery/" rel="tag"># jQuery</a>
          
            <a href="/tags/AJAX/" rel="tag"># AJAX</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/28/test1/" rel="next" title="课后题">
                <i class="fa fa-chevron-left"></i> 课后题
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/08/31/fiex/" rel="prev" title="伸缩盒子(flex)">
                伸缩盒子(flex) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="Key">
            
              <p class="site-author-name" itemprop="name">Key</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">107</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">28</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/keyarea" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:wxkayle@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#AJAX技术"><span class="nav-number">1.</span> <span class="nav-text">AJAX技术</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#原生XHR对象应用"><span class="nav-number">2.</span> <span class="nav-text">原生XHR对象应用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#创建XMLHttpRequest对象"><span class="nav-number">2.1.</span> <span class="nav-text">创建XMLHttpRequest对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#open-初始化一个请求"><span class="nav-number">2.2.</span> <span class="nav-text">open() 初始化一个请求</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#send-发送一个请求"><span class="nav-number">2.3.</span> <span class="nav-text">send() 发送一个请求</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#接受响应"><span class="nav-number">2.4.</span> <span class="nav-text">接受响应</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#GET请求"><span class="nav-number">2.5.</span> <span class="nav-text">GET请求</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#POST请求"><span class="nav-number">2.6.</span> <span class="nav-text">POST请求</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#jQuery-中的-Ajax-应用"><span class="nav-number">3.</span> <span class="nav-text">jQuery 中的 Ajax 应用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#底层接口"><span class="nav-number">3.1.</span> <span class="nav-text">底层接口</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#常用的选项"><span class="nav-number">3.1.1.</span> <span class="nav-text">常用的选项</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#实例–登录"><span class="nav-number">3.1.2.</span> <span class="nav-text">实例–登录</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-snowflake-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Key</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">190.8k</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
